<?php


namespace App\Biz;


use App\Model\AwardsRecordModel;
use App\Model\LuckyOrderModel;
use App\Model\StageModel;
use App\Model\StageUserModel;

use App\Model\UserModel;
use EasySwoole\Component\Di;
use EasySwoole\ORM\DbManager;
use EasySwoole\RedisPool\Redis;
use priestll\easyswoole\biz\BaseBiz;
use priestll\easyswoole\queue\Job;
use priestll\easyswoole\queue\Queue;
use priestll\easyswoole\util\Token;


class OrderBiz extends BaseBiz
{
    const RANKING_KEY="order_ranking";//redis key
    const RANKING_LIMIT=50; //排行榜人数
    const EXPRIRE=60; //过期时间
    const PAGESIZE=10;

    public function getRanking($round,$page)
    {
        if ($round < 1 || $round > 6) {
            return $this->fail("invalid param");
        }
        if (!$page) $page=1;
        $redis = Redis::defer(self::DEF_REDIS);
        $key   = self::RANKING_KEY . "_" . $round."_".$page;
        if (!$redis->exists($key)) {
            $ranking = LuckyOrderModel::create()
                ->field(["FROM_UNIXTIME(created_at,'%m.%d %H:%i') as created_at", "nickname"])
                ->where(["round" => $round])
                ->order("created_at", "asc")
                ->limit(($page-1)*self::PAGESIZE,self::PAGESIZE)
                ->all();
            $count=LuckyOrderModel::create()->where(["round" => $round])->count();
            if ($ranking)
            {
                $ranking=["count"=>$count,"page"=>$page,"data"=>$ranking];
            }
            else
            {
                $ranking=["count"=>0,"page"=>$page,"data"=>[]];
            }
            $ranking = json_encode($ranking);
            $redis->set($key, $ranking, self::EXPRIRE);
        } else {
            $ranking = $redis->get($key);
        }
        return $this->success(json_decode($ranking,true));
    }

    public function confirm($user_id)
    {
        $user=Di::getInstance()->get('USER_BIZ')->getTokenUser("id",$user_id);
        if ($user->round>6) {
            return $this->fail("已达最后一轮");
        }
        if ($user->round==6)
        {
            $check=LuckyOrderModel::create()->where(["userid"=>$user->id,"round"=>$user->round])->count();
            if (!$check)
            {
                $db = DbManager::getInstance();
                try {
                    //开启事务
                    $db->startTransaction();
                    $order = new LuckyOrderModel();
                    $res   = $order->data([
                        'userid' => $user->id,
                        'round' => $user->round,
                        'power' => 1,
                        'nickname' => $user->nickname,
                        'avatar' => $user->avatar
                    ])->save();
                    if (!$res)
                    {
                        throw new \Exception("请重新点亮!");
                    }
                    $user->award_times=1;
                    if (!$user->update())
                    {
                        throw new \Exception("请重新点亮!");
                    }
                    $token = Token::getInstance();
                    $newToken = $token->create($user->toArray());
                    $db->commit();
                    return $this->success(["token"=>$newToken,"round"=>$user->round]);
                } catch (\Throwable  $e) {
                    //回滚事务
                    $db->rollback();
                    return $this->fail($e->getMessage());
                }
            }
            return $this->fail("已点亮星河!");
        }
        $stage=StageModel::create()
            ->alias("s")
            ->field(["s.power","count(l.id) as current_power"])
            ->join("tv_lucky_stage_log as l","l.assist_id={$user->id} AND l.round=s.id","left")
            ->where(["s.id"=>$user->round])
            ->limit(1)
            ->get();
        if ($stage&&$stage->power<=$stage->current_power)
        {
            $db = DbManager::getInstance();
            try {
                //开启事务
                $db->startTransaction();
                $order = new LuckyOrderModel();
                $res   = $order->data([
                    'userid' => $user->id,
                    'round' => $user->round,
                    'power' => $stage->power,
                    'nickname' => $user->nickname,
                    'avatar' => $user->avatar
                ])->save();
                if (!$res)
                {
                    throw new \Exception("INSERT tv_lucky_order_list FAILE");
                }
                $user->round++;
                $user->award_times=1;
                if (!$user->update())
                {
                    throw new \Exception("UPDATE tv_lucky_user FAILE");
                }
                $token = Token::getInstance();
                $newToken = $token->create($user->toArray());
                //提交事务
                $db->commit();
                return $this->success(["token"=>$newToken,"round"=>$user->round]);
            } catch (\Throwable  $e) {
                //回滚事务
                $db->rollback();
                return $this->fail($e->getMessage());
            }
        }
        else
        {
            return $this->fail("助力值未达标,请加油!");
        }

    }
}